package pakn.backing;

import common.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import java.util.List;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;

import javax.servlet.http.HttpServletRequest;

import nl.captcha.Captcha;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout;

import oracle.adf.view.rich.component.rich.output.RichOutputText;

import org.apache.myfaces.trinidad.model.UploadedFile;

import util.MailImplement;

public class paknBacking {
    private UploadedFile _file;
    private String answer;
    private String tieudeportlet;
    private static String mailnoinhan;
    private String viewRender;
    private String ketqua = "";
    //Components
    private RichPanelFormLayout formlayout;
    private RichOutputText rotKetqua = new RichOutputText();
    private RichInputText txtHoten = new RichInputText();
    private RichInputText txtEmailnguoigui = new RichInputText();
    private RichInputText txtTieude = new RichInputText();
    private RichInputText txtNoidung = new RichInputText();
    
    public paknBacking(){
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            ketqua = "";
            rotKetqua.setVisible(false);
        } 
    }

    public String getViewRender() {
        return viewRender;
    }

    public void send(ActionEvent actionEvent) {
        if (capcha()) {
            try {
                boolean fileupload = true;
                File filePath =
                    new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                             Utils.ENUM_CAU_HINH_KHOA.PAKN_DIR.getValue("HtCauHinhView1Iterator"));
                File duongdantuongdoi =
                    new File(Utils.ENUM_CAU_HINH_KHOA.PAKN_DIR.getValue("HtCauHinhView1Iterator"));
                DCIteratorBinding IteratorPakn =
                    Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
                IteratorPakn.getCurrentRow().setAttribute("NgayGui",
                                                          Utils.getCurrentDate().dateValue().toString());
                UploadedFile file = this.getFile();
                File obj = null;
                FileOutputStream output = null;
                Object fileId = null;
                DCIteratorBinding fileIterator1 =
                    Utils.getIteratorBinding("HtFileView1Iterator");
                if (file != null) {
                    String fileName = file.getFilename();
                    if (Utils.checkDefaultFileExtension(fileName)) {
                        try {
                            if (filePath.exists() == false) {
                                filePath.mkdirs();
                            }
                            byte buffer[] = new byte[1024];
                            int size = 0;
                            InputStream input = file.getInputStream();
                            Utils.execute("HtFileInsert");
                            fileId =
                                    fileIterator1.getCurrentRow().getAttribute("Id");

                            output =
                                    new FileOutputStream(new File(filePath, fileId +
                                                                  "_" +
                                                                  fileName));
                            while ((size = input.read(buffer)) != -1) {
                                output.write(buffer);
                            }
                            obj = new File(filePath, fileId + "_" + fileName);
                            Utils.processUpload(file, duongdantuongdoi,
                                                "HtFileView1Iterator",
                                                "PhanAnhKienNghiView1Iterator",
                                                Utils.ENUM_MA_UNG_DUNG.PAKN,
                                                fileId.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (output != null) {
                                try {
                                    output.flush();
                                    output.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        this.setFile(null);
                        this.setAnswer(null);
                        ketqua = getFileHopLeLabel();
                        rotKetqua.setInlineStyle("color:red;");
                        rotKetqua.setVisible(true);
                        Utils.getPortletRequest().getPortletSession().setAttribute("unreset",
                                                                                   2);
                        fileupload = false;
                    }
                }
                if (fileupload) {
                    if (sendmail(obj)) {
                        if (Utils.execute("Commit") == null) {
                            this.setFile(null);
                            this.setAnswer(null);
                            Utils.iteratorRefresh("PhanAnhKienNghiView1Iterator");
                            Utils.execute("CreateInsert");
                            ketqua = getGuiThanhCongLabel();
                            rotKetqua.setInlineStyle("color:blue;");
                            rotKetqua.setVisible(true);
                        }
                        else{
                            ketqua = getGuiKhongThanhCongLabel();
                            rotKetqua.setInlineStyle("color:red;");
                            rotKetqua.setVisible(true);                                
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            if (this.getAnswer() != null) {
                ketqua = getNhapMaXacNhanLabel();
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setFile(null);
                this.setAnswer(null);
            } else {
                ketqua = getNhapMaXacNhanLabel();
                rotKetqua.setInlineStyle("color:red;");
                rotKetqua.setVisible(true);
                this.setFile(null);
            }
            Utils.getPortletRequest().getPortletSession().setAttribute("unreset",
                                                                       2);
        }
    }

    public boolean sendmail(File file) {
        boolean mSent = true;
        MailImplement mail = new MailImplement();
        String hoten = txtHoten.getValue().toString();
        String tieudemail = txtTieude.getValue().toString();
        String mailnguoigui = txtEmailnguoigui.getValue().toString();
        String noidungmail = txtNoidung.getValue().toString();
        String emailnhan = mailnoinhan;
        try {
            mail.sendEmail(emailnhan, tieudemail, noidungmail, mailnguoigui,
                           file);
            mSent = true;
        } catch (Exception mse) {
            mSent = false;
        }
        return mSent;
    }

    /**
     * Author       Date        Comment
     *  TớiNT    09/11/2012     Kiểm tra captcha
     * @return
     */
    public boolean capcha() {
        try {
            HttpServletRequest httpServletRequest =
                (HttpServletRequest)Utils.getPortletRequest().getAttribute("javax.servlet.request");
            if (httpServletRequest != null) {
                Captcha captcha =
                    (Captcha)httpServletRequest.getSession().getAttribute(Captcha.NAME);
                if (captcha != null && this.getAnswer() != null) {
                    if (captcha.isCorrect(this.getAnswer())) {
                        return true;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public void beforePhase(PhaseEvent phaseEvent) {
        try {
            Integer reset =
                (Integer)Utils.getPortletRequest().getPortletSession().getAttribute("reset");
            if (reset != null && reset == 1) {
                Utils.getPortletRequest().getPortletSession().setAttribute("reset",
                                                                           0);
                Utils.execute("Rollback");
                Utils.execute("CreateInsert");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFile(UploadedFile _file) {
        this._file = _file;
    }

    public UploadedFile getFile() {
        return _file;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getAnswer() {
        return answer;
    }

    public void setTxtHoten(RichInputText txtHoten) {
        this.txtHoten = txtHoten;
    }

    public RichInputText getTxtHoten() {
        return txtHoten;
    }

    public void setTxtEmailnguoigui(RichInputText txtEmailnguoigui) {
        this.txtEmailnguoigui = txtEmailnguoigui;
    }

    public RichInputText getTxtEmailnguoigui() {
        return txtEmailnguoigui;
    }

    public void setTxtTieude(RichInputText txtTieude) {
        this.txtTieude = txtTieude;
    }

    public RichInputText getTxtTieude() {
        return txtTieude;
    }

    public void setTxtNoidung(RichInputText txtNoidung) {
        this.txtNoidung = txtNoidung;
    }

    public RichInputText getTxtNoidung() {
        return txtNoidung;
    }

    public void setFormlayout(RichPanelFormLayout formlayout) {
        this.formlayout = formlayout;
    }

    public RichPanelFormLayout getFormlayout() {
        return formlayout;
    }

    public void setMailnoinhan(String mailnoinhan) {
        this.mailnoinhan = mailnoinhan;
    }

    public String getMailnoinhan() {
        mailnoinhan = "tanbd@tinhvan.com";
        try {
            if (Utils.getPortletRequest().getParameter("emailnoinhan") != null)
                mailnoinhan =
                        Utils.getPortletRequest().getParameter("emailnoinhan").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mailnoinhan;
    }

    public void setRotKetqua(RichOutputText rotKetqua) {
        this.rotKetqua = rotKetqua;
    }

    public RichOutputText getRotKetqua() {
        return rotKetqua;
    }

    public void setKetqua(String ketqua) {
        this.ketqua = ketqua;
    }

    public String getKetqua() {
        return ketqua;
    }

    public String getTieudeportlet() {
        tieudeportlet = Utils.getResource("TIEU_DE_PAKN");
        try {
            if (Utils.getPortletRequest().getParameter("tieudeportlet") !=
                null)
                tieudeportlet =
                        Utils.getPortletRequest().getParameter("tieudeportlet").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tieudeportlet;
    }

    public String getHoVaTenLabel() {
        String resource = Utils.getResource("HO_TEN");
        return resource;
    }

    public String getNhapHoVaTen() {
        String resource = Utils.getResource("NHAP_HO_VA_TEN");
        return resource;
    }

    public String getNhaptieude() {
        String resource = Utils.getResource("NHAP_TIEU_DE");
        return resource;
    }

    public String getEmail() {
        String resource = Utils.getResource("EMAIL");
        return resource;
    }

    public String getNhapDiaChiMail() {
        String resource = Utils.getResource("NHAP_DIA_CHI_MAIL");
        return resource;
    }

    public String getNhapSaiDinhDangMail() {
        String resource = Utils.getResource("NHAP_SAI_DINH_DANG_MAIL");
        return resource;
    }

    public String getTieuDeLabel() {
        String resource = Utils.getResource("TIEU_DE");
        return resource;
    }

    public String getNoiDungGopyLabel() {
        String resource = Utils.getResource("NOI_DUNG_GOP_Y");
        return resource;
    }

    public String getNhapNoiDung() {
        String resource = Utils.getResource("NHAP_NOI_DUNG");
        return resource;
    }

    public String getGuiPAKNButton() {
        String resource = Utils.getResource("GUI_PAKN");
        return resource;
    }

    public String getChonfileLabel() {
        String resource = Utils.getResource("CHON_FILE");
        return resource;
    }

    public String getMaxacnhanLabel() {
        String resource = Utils.getResource("MA_XAC_NHAN");
        return resource;
    }

    public String getDoiMaKhac() {
        String resource = Utils.getResource("DOI_MA_KHAC");
        return resource;
    }

    public String getFileSizeError() {
        String resource = Utils.getResource("FILE_SIZE_INVALID");
        return resource;
    }

    public String getFileLabel() {
        String resource = Utils.getResource("LABLE_GIOIHAN_FILE");
        return resource;
    }

    public String getGuiThanhCongLabel() {
        String resource = Utils.getResource("GUI_THANH_CONG");
        return resource;
    }

    public String getGuiKhongThanhCongLabel() {
        String resource = Utils.getResource("GUI_KHONG_THANH_CONG");
        return resource;
    }

    public String getXacNhanSaiLabel() {
        String resource = Utils.getResource("SAI_MA_XAC_NHAN");
        return resource;
    }

    public String getNhapMaXacNhanLabel() {
        String resource = Utils.getResource("NHAP_MA_XAC_NHAN");
        return resource;
    }

    public String getFileHopLeLabel() {
        String resource = Utils.getResource("FILE_HOP_LE");
        return resource;
    }
}
